package com.atguigu.gulimall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryBrandRelationService;
import com.atguigu.gulimall.product.service.CategoryService;
import com.atguigu.gulimall.product.vo.Categlog2Vo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    CategoryBrandRelationService categoryBrandRelationService;
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    RedissonClient redisson;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> queryTree() {
        //1、查出所有分类
        List<CategoryEntity> entities = baseMapper.selectList(null);

        //List<CategoryEntity> entities = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("cat_id", 21));

        /**
         * filter 结果为false的过滤掉
         */
        List<CategoryEntity> level1Menus = entities.stream().filter(categoryEntity ->
                categoryEntity.getParentCid() == 0 //找出父id为0的
        ).map((menu)->{
            //设置子节点
            menu.setChildren(getChildrens(menu,entities));
            return menu;
        }).sorted((menu1,menu2)-> {
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());

        return level1Menus;
    }

    /**
     * 删除
     * @param longs
     */
    @Override
    public void removeAllId(List<Long> longs) {
        //TODO 1.检查id是否有关联项
        baseMapper.deleteBatchIds(longs);
    }

    /**
     * 根据分类id查询分类路径
     * @param catelogId
     * @return
     */
    @Override
    public Long[] queryCategoryIdPath(Long catelogId) {
        //创建1个list集合 把分类id放进list集合中
        List<Long> paths = new ArrayList<>();
        List<Long> longs = queryId(catelogId, paths);
        Collections.reverse(longs);//反转集合内容
        return (Long[]) longs.toArray(new Long[longs.size()]);
    }

    /**
     * 关联修改
     * @param category
     */
    @Override
    @Transactional
    public void updateByIdDeail(CategoryEntity category) {
        this.updateById(category);
        if (!StringUtils.isEmpty(category.getName())){
            //关联修改
            categoryBrandRelationService.updateCategory(category.getCatId(),category.getName());
        }
    }

    /**
     *查询1级分类
     * @return
     */
    @Cacheable(value = "category")
    @Override
    public List<CategoryEntity> selectLevel1() {
        return baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid",0));
    }

    /**
     * 获取所有二级分类和三级分类
     * @return
     */
    @Override
    public Map<String,List<Categlog2Vo>> getCategory23() {
        //查询redis缓存是否有数据
        String category = redisTemplate.opsForValue().get("category");
        if (StringUtils.isEmpty(category)){
            //查询数据库
            Map<String, List<Categlog2Vo>> category23db = this.getCatce();
            return category23db;
        }
        Map<String, List<Categlog2Vo>> stringListMap = JSON.parseObject(category, new TypeReference<Map<String, List<Categlog2Vo>>>() {
        });
        return stringListMap;
    }

    /**
     * 缓存里面的数据 分布式闭锁
     * @return
     */
    public Map<String,List<Categlog2Vo>> getCatce() {
        RLock category = redisson.getLock("category23");
        category.lock();//加锁 默认加的锁时30s
        Map<String, List<Categlog2Vo>> stringListMap;
        try {
            stringListMap = this.getCategory23db();
        }finally {
            if (category.isLocked()){
                if (category.isHeldByCurrentThread()){ //
                    category.unlock();//解锁
                }
            }
        }
        return stringListMap;
    }
    /**
     * 通过从数据库中查询三级分类
     * @return
     */
    public Map<String,List<Categlog2Vo>> getCategory23db() {

        //判断缓存中是否有数据
        String category = redisTemplate.opsForValue().get("category");
        if (!StringUtils.isEmpty(category)){
            Map<String, List<Categlog2Vo>> stringListMap = JSON.parseObject(category, new TypeReference<Map<String, List<Categlog2Vo>>>() {
            });
            return stringListMap;
        }
        //获取所有分类
        List<CategoryEntity> selectList = this.baseMapper.selectList(null);
        //获取1级分类
        List<CategoryEntity> list = selectLevel1();
        //k -> k.getCatId().toString()
        Map<String, List<Categlog2Vo>> parent_cid = list.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            //查找二级分类
            List<CategoryEntity> list1 = getParent_cid(selectList,v.getCatId());
            List<Categlog2Vo> categlog2Vos = null;
            if (list1 != null) {
                categlog2Vos = list1.stream().map(item -> {

                    Categlog2Vo categlog2Vo = new Categlog2Vo(v.getCatId().toString(), null, item.getCatId().toString(), item.getName());
                    //查找三级分类
                    List<CategoryEntity> list2 = getParent_cid(selectList,item.getCatId());

                    if (baseMapper!=null){
                        List<Categlog2Vo.Categlog3Vo> collect = list2.stream().map(item2 -> {
                            Categlog2Vo.Categlog3Vo categlog3Vo = new Categlog2Vo.Categlog3Vo(item.getCatId().toString(),item2.getCatId().toString(),item2.getName());
                            return categlog3Vo;
                        }).collect(Collectors.toList());
                        categlog2Vo.setCatalog3List(collect);
                    }
                    return categlog2Vo;
                }).collect(Collectors.toList());
            }
            return categlog2Vos;
        }));
        String s = JSON.toJSONString(parent_cid);
        //放入redis缓存中
        redisTemplate.opsForValue().set("category",s);
        return parent_cid;
    }

    private List<CategoryEntity> getParent_cid(List<CategoryEntity> selectList, Long parent_cid) {
        List<CategoryEntity> collect = selectList.stream().filter(item -> item.getParentCid() == parent_cid).collect(Collectors.toList());
        return collect;
    }

    //递归查询分类id
    public List<Long> queryId(Long catelogId,List<Long> paths){
        //先把分类id放入集合中
        paths.add(catelogId);
        //根据分类id查询数据
        CategoryEntity byId = this.getById(catelogId);
        //判断父id是否为空
        if (byId.getParentCid()!=0){
            //递归查询
            queryId(byId.getParentCid(),paths);
        }
        return paths;
    }

    /**
     *
     * @param root 当前菜单
     * @param all 所有菜单
     * @return
     */
//    private List<CategoryEntity> getChildrens(CategoryEntity root,List<CategoryEntity> all){
//        List<CategoryEntity> collect = all.stream().filter(categoryEntity -> {
//            return categoryEntity.getParentCid() == root.getCatId();
//        }).map((categoryEntity) -> {
//            categoryEntity.setChildrens(getChildrens(categoryEntity, all));
//            return categoryEntity;
//        }).sorted((menu1, menu2) -> {
//            return (menu1.getSort()==null?0:menu1.getSort()) - (menu2.getSort()==null?0:menu2.getSort());
//        }).collect(Collectors.toList());
//        return collect;
//    }

    //递归查找所有菜单的子菜单

    /**
     *
     * @param root 父节点
     * @param all 所有节点
     * @return
     */
    private List<CategoryEntity> getChildrens(CategoryEntity root,List<CategoryEntity> all){

        List<CategoryEntity> children = all.stream().filter(categoryEntity -> {
            return categoryEntity.getParentCid() == root.getCatId();
        }).map(categoryEntity -> {
            //1、找到子菜单
            categoryEntity.setChildren(getChildrens(categoryEntity,all));
            return categoryEntity;
        }).sorted((menu1,menu2)->{
            //2、菜单的排序
            return (menu1.getSort()==null?0:menu1.getSort()) - (menu2.getSort()==null?0:menu2.getSort());
        }).collect(Collectors.toList());

        return children;
    }
}